package com.czx.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@Controller
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @RequestMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();
        // 将验证码文本存储到Session或缓存中
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        // 将验证码图片写入响应流
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
